package com.kkw.shoppingmall.cart.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.kkw.common.utils.R;
import com.kkw.shoppingmall.cart.feign.ProductFeignService;
import com.kkw.shoppingmall.cart.interceptor.CartInterceptor;
import com.kkw.shoppingmall.cart.service.CartService;
import com.kkw.shoppingmall.cart.vo.Cart;
import com.kkw.shoppingmall.cart.vo.CartItem;
import com.kkw.shoppingmall.cart.vo.SkuInfoVo;
import com.kkw.shoppingmall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author Kevin
 * @date 2021-06-11
 **/
@Slf4j
@Service
public class CartServiceImpl implements CartService {


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    private final String CART_PREFIX = "shoppingmall:cart";

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String res = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(res)) {
            //2、添加新商品到购物车
            CartItem cartItem = new CartItem();
            //1、远程查询当前要添加的商品的信息
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                R skuInfo = productFeignService.getSkuInfo(skuId);
                SkuInfoVo data = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItem.setCheck(true);
                cartItem.setImage(data.getSkuDefaultImg());
                cartItem.setTitle(data.getSkuTitle());
                cartItem.setSkuId(skuId);
                cartItem.setCount(num);
                cartItem.setPrice(data.getPrice());
            }, executor);

            //2、远程查询sku的组合信息
            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                List<String> values = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(values);
            }, executor);

            //一定要等异步任务全部完成 否则会都是空值
            CompletableFuture.allOf(getSkuInfoTask, getSkuSaleAttrValues).get();

            //默认用的是jdk的序列化  所以我们先把他转换成json，然后在放入redis里面
            String s = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), s);
            return cartItem;
        } else {
            //购物车有此商品，修改数量
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            //放入缓存再返回出去
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        }


    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String str = (String) cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(str, CartItem.class);
        return cartItem;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null) {
            //1、登录
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            //2、如果还有临时购物车的数据 我们就需要进行合并
            List<CartItem> tempCartItems = getCartItems(CART_PREFIX + userInfoTo.getUserKey());
            if (tempCartItems != null) {
                //证明临时购物车有数据，需要合并
                for (CartItem item : tempCartItems) {
                    addToCart(item.getSkuId(), item.getCount());
                }
                //合并完后记得清空购物车
                clearCart(CART_PREFIX + userInfoTo.getUserKey());
            }
            //3、获取登陆后的购物车的数据(包含合并过来的临时购物车数据，和登录后购物车的数据)
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);


        } else {
            //2、没登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            //获取临时购物车的登录状态
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }
        return cart;
    }


    /**
     * 获取到我们要操作的购物车
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        //存在redis里的hash key是用户的id 获取临时用户的key
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        //1、
        if (userInfoTo.getUserId() != null) {
            //shoppingmall:cart:1
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            //临时购物车
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        //不使用这个
//        redisTemplate.opsForHash().get(cartKey,"1")
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }


    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (values != null && values.size() > 0) {
            List<CartItem> collect = values.stream().map(obj -> {
                String str = (String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        //获取不到则返回null
        return null;
    }


    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1 ? true : false);
        //设置redis里面skuId对应的状态值
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), s);

    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        //获取到我们要操作的购物车
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        //获取购物车的一个购物项
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        String str = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), str);
    }

    @Override
    public void deleteItem(Long skuId) {
        //获取到我们要操作的购物车
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null) {
            //只有登录的情况下 才给他返回购物车的数据
            return null;
        } else {
            //为什么要加map 因为要实时获取购物车里面商品的最新价格
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            List<CartItem> collect = cartItems.stream()
                    .filter(obj -> obj.getCheck())
                    .map(item->{
                        R price = productFeignService.getPrice(item.getSkuId());
                        String data =(String) price.get("data");
                        item.setPrice(new BigDecimal(data));
                        return item;
                    })
                    .collect(Collectors.toList());

            //获取所有被选中的购物项
            return collect;
        }
    }
}
